class Service {
  _db = null;

  constructor(tableName, insertKeys = [], updateKeys = []) {
    this.tableName = tableName;
    this.insertKeys = insertKeys;
    this.updateKeys = updateKeys;
  }

  get db() {
    return this._db;
  }

  set db(val) {
    this._db = val
  }

  async get(id) {
    return await this.db(this.tableName).select().where({ id }).first();
  }

  async list(page, pageSize) {
    if (page <= 0) {
      page = 1;
    }

    const totalRes = await this.db(this.tableName).count().first();
    const list = await this.db(this.tableName)
      .select("*")
      .limit(pageSize)
      .offset((page - 1) * pageSize);
    return {
      list,
      page,
      pageSize,
      total: totalRes?.["count(*)"] || 0,
    };
  }

  async insert(data) {
    const insertData = {};

    this.insertKeys.forEach((k) => {
      insertData[k] = data[k];
    });

    return await this.db.insert(insertData).into(this.tableName);
  }

  async update(id, data) {
    const updateData = {};

    this.updateKeys.forEach((k) => {
      updateData[k] = data[k];
    });

    return await this.db(this.tableName).where({ id }).update(updateData);
  }

  async del(id) {
    return await this.db(this.tableName).where({ id }).del();
  }
}

module.exports = Service;
